package security;

import org.bouncycastle.util.encoders.Base64;

/**
 * Helper class to Base64-encode and -decode Messages
 * @author Group 95
 */
public class Base64Coder 
{
    public static String decode(String str)
    {
        return new String(decodeByte(str));
    }
    
    public static String decode(byte [] b)
    {
        return new String(decodeByte(b));
    }    

    public static byte[] decodeByte(String str)
    {
        return decodeByte(str.getBytes());
    }    

    public static byte[] decodeByte(byte [] b)
    {
        return Base64.decode(b);
    }    
        
    public static String encode(String str)
    {
        return encode(str.getBytes());
    }
    
    public static String encode(byte [] b)
    {
        return new String(Base64.encode(b));
    }    
    
    public static String base64decodeParts(String strMessage)
    {
        String[] strParts=strMessage.split(" ");
        StringBuilder strB=new StringBuilder(strMessage.length());
        for(String s:strParts)
        {
            strB.append(new String(Base64.decode(s.getBytes()))).append(" ");
        }
        strB.deleteCharAt(strB.length()-1);
        return strB.toString();        
    }
    
    
    public static byte[] base64decodeParts(byte[] message)
    {
        String strMessage=new String(message);
        String[] strParts=strMessage.split(" ");
        StringBuilder strB=new StringBuilder(strMessage.length());
        for(String s:strParts)
        {
            strB.append(new String(Base64.decode(s.getBytes()))).append(" ");
        }
        strB.deleteCharAt(strB.length()-1);
        return strB.toString().getBytes();        
    }    
    
    public static String base64encodeParts(String strMessage)
    {
        String[] strParts=strMessage.split(" ");
        StringBuilder strB=new StringBuilder(strMessage.length());
        for(String s:strParts)
        {
            strB.append(new String(Base64.encode(s.getBytes()))).append(" ");
        }
        strB.deleteCharAt(strB.length()-1);
        return strB.toString();        
    }    
}
